import logging
from loguru import logger

from apps.Order.models import Order
from op_drf.dj_utils import create_by_serializer, flow_code_manage, check_serial_num
from op_drf.serializers import CustomModelSerializer, BaseSerializer
from rest_framework import serializers
from apps.prescription.models import (
Prescription,
Drug
)

import datetime

# 新建处方信息
class WriteOrderSerializer(CustomModelSerializer):
    order_date = serializers.DateField(format="%Y-%m-%d",default=datetime.datetime.now())
    # OrderNum = serializers.CharField(required=True)
    # # 默认专业方
    # OrderType = serializers.CharField(default="0")

    def create(self, validated_data):
        # 增加数据的验证
        serial_num = flow_code_manage(value="order_num")
        check_serial_num(serial_num=serial_num, model=self.Meta.model, check_field_name="ordernum")
        validated_data["ordernum"] = serial_num
        logger.debug("请求携带的数据： %s" % validated_data)
        instance = super().create(validated_data)
        instance.prescription.OrderStatus = "1"
        instance.prescription.save()
        return instance

    class Meta:
        model = Order
        fields = "__all__"


'''
读取订单列表
'''
class ReadOrderSerializer(BaseSerializer):
    order_date = serializers.DateField(format="%Y-%m-%d")
    Prescription_Num = serializers.CharField(source="prescription.OrderNum",read_only=True)
    OrderStatus_name = serializers.SerializerMethodField(read_only=True)
    rad_name = serializers.SerializerMethodField(read_only=True)

    def get_OrderStatus_name(self, obj):
        if obj.OrderStatus:
            if obj.OrderStatus=="1":
                return "已购药"
            else:
                return "未购药"

    def get_rad_name(self, obj):
        if obj.rad:
            return f'{obj.rad.name}-{obj.rad.place}' if obj.rad else ""

    class Meta:
        model = Order
        fields = "__all__"

